import userApi from "@/api/modules/user";
const user = {
  namespaced: true,
  state: {
    // 令牌
    token: sessionStorage.getItem("token") || "",
    userName: "",
    permission: null
  },
  mutations: {
    setToken(state, Token) {
      state.token = Token;
      sessionStorage.setItem("token", Token);
    },
    setPermission(state, Arr) {
      state.permission = Arr;
    },
    setUserName(state, name) {
      state.userName = name;
    }
  },
  actions: {
    // user login
    login({ commit }, parmas) {
      return new Promise((resolve, reject) => {
        userApi
          .login(parmas)
          .then(res => {
            commit("setToken", res.data.token);
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    getUserInfo({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        userApi
          .getUserInfo()
          .then(async res => {
            commit("setPermission", res.data.permission);
            commit("setUserName", res.data.userName);
            await dispatch("permission/getAsyncRoutes", res.data.permission, {
              root: true
            });
            resolve(res.data);
          })
          .catch(err => {
            reject(err);
          });
      });
    }
  }
};
export default user;
